package com.mediacloud.app.newsmodule.fragment.audio.live

import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebSettings
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.util.WebViewUtils
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.fragment_program_home_intro.*

/**
 * 简介
 */
class AudioLiveColumnHomeIntroFragment : HqyNavFragment() {

    private var programArticleItem: ArticleItem? = null

    companion object {
        fun newInstance(
            title: String? = "",
            articleItem: ArticleItem?
        ): AudioLiveColumnHomeIntroFragment {
            val fragment = AudioLiveColumnHomeIntroFragment()
            val bundle = Bundle()
            bundle.putString("title", title)
            bundle.putParcelable("data", articleItem)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.fragment_program_home_intro
    }

    override fun initArgs() {
        super.initArgs()
        programArticleItem = arguments?.getParcelable("data")
    }

    override fun initView() {
        loadingView = mLoadingView
        initStateView()
        initWebView()
    }

    /**
     * 初始化浏览器
     */
    fun initWebView() {
        val webSetting: WebSettings = webView.getSettings()
        webSetting.javaScriptEnabled = true
        webSetting.textSize = WebSettings.TextSize.NORMAL
        webSetting.javaScriptCanOpenWindowsAutomatically = true
        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls =
            true // 设置出现缩放工具 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false
        webSetting.displayZoomControls = false //隐藏缩放工具
        webSetting.useWideViewPort = true //// 扩大比例的缩放
        webSetting.loadWithOverviewMode = true
        webSetting.savePassword = false //保存密码
        webSetting.saveFormData = true
        webSetting.databaseEnabled = true
        webSetting.loadsImagesAutomatically = true ////图片自动缩放 打开
        webSetting.defaultTextEncodingName = "utf-8" //设置编码格式
        webSetting.defaultFontSize = 16 //设置 WebView 字体的大小，默认大小为 16
        webSetting.minimumFontSize = 8 //设置 WebView 支持的最小字体大小，默认为 8
        //        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//关闭硬件加速器
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val cookieManager = CookieManager.getInstance()
            cookieManager.setAcceptThirdPartyCookies(webView, true)
            //            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//关闭软件加速器
        }
        webSetting.setGeolocationEnabled(true) //启用地理定位
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //webview在安卓5.0之前默认允许其加载混合网络协议内容
            // 在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
            webSetting.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        // 设置4.2以后版本支持autoPlay，非用户手势促发    在android 4.2添加了允许用户手势触发音视频播放接口，该接口默认为 true ，即默认不允许自动播放音视频，只能是用户交互的方式由用户自己促发播放。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSetting.mediaPlaybackRequiresUserGesture = false
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSetting.allowUniversalAccessFromFileURLs = true
            webSetting.allowFileAccessFromFileURLs = true
            webSetting.allowContentAccess = true
            if (Build.VERSION.SDK_INT >= 33) {
                webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
            } else {
                webSetting.setAppCacheEnabled(true)
            }
        }
        WebViewUtils.setCache(requireContext(), webView)
    }

    override fun onResume() {
        super.onResume()
        webView.onResume()
        webView.resumeTimers()
    }

    override fun onPause() {
        super.onPause()
        webView.pauseTimers()
        webView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        WebViewUtils.clearCache(webView)
    }

    override fun initOther() {
        super.initOther()

        initListener()

        updateUI(programArticleItem)
    }


    private fun initListener() {

    }

    fun updateUI(articleItem: ArticleItem?) {
        if (activity == null || requireActivity().isFinishing) {
            return
        }
        this.programArticleItem = articleItem
        var contentStr: String? = ""
        if (!TextUtils.isEmpty(articleItem?.getContent())) {
            contentStr = articleItem?.getContent()
        }
        try {
            MMKV.defaultMMKV().getString(XKey.BASE_JS_STRING, "")?.let {
                MMKV.defaultMMKV().getString(XKey.BASE_JS_STRING_HEAD, "")?.let { it1 ->
                    contentStr = contentStr?.replace("#appfactoryContentJS#", it)
                        ?.replace("#appfactoryContentJSHead#", it1)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        contentStr?.let {
            webView.loadDataWithBaseURL(null, it, "text/html", "UTF-8", null)
        }

        webView.post {
            closeStateView()
            if (webView.visibility == View.GONE) {
                webView.visibility = View.VISIBLE
            }
        }
    }

}